package com.fileshare.web.service.impl;

import com.fileshare.web.entity.User;
import com.fileshare.web.properties.EmailProperties;
import com.fileshare.web.service.EmailService;
import com.fileshare.web.utils.EmailUtil;
import com.fileshare.web.utils.EmailUtil.EmailParameter;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
public class EmailServiceImpl implements EmailService {
    @Resource
    private EmailProperties emailProperties;
    @Resource
    private TemplateEngine templateEngine;

    @Override
    public void sendWelcomeNotification(User user) {
        Context context = new Context();
        HashMap<String, Object> paramMap = new HashMap<>(16);
        paramMap.put("gender", user.getGender());
        paramMap.put("userName", user.getNickName());
        paramMap.put("avatar", user.getAvatar());
        paramMap.put("userHomeUrl", "https://www.senler.com/" + user.getUserName());
        paramMap.put("joinCount", user.getJoinCount());
        context.setVariables(paramMap);
        String emailContent = templateEngine.process("email/welcome", context);
        EmailUtil.EmailParameter parameter = getEmailParameter(user, emailContent, "欢迎加入！");
        EmailUtil.send(parameter);
    }

    private EmailParameter getEmailParameter(User user, String emailContent, String subject) {
        return EmailUtil.EmailParameter.builder()
                .account(emailProperties.getAccount())
                .password(emailProperties.getSecret())
                .debug(true)
                .content(emailContent)
                .attaches(null)
                .sender(emailProperties.getAccount())
                .receivers(user.getEmail())
                .subject(subject)
                .host("smtp.exmail.qq.com")
                .port("465")
                .protocol("smtp")
                .build();
    }
}
